
const app = getApp()
const db = wx.cloud.database();
const _ = db.command
var util = require('../getTime/getTime.js');
let teacherLatitude = null
let teacherLongitude = null
let teacherTimeStamp = null
let scene = null
Page({
// 计算两地之间的距离
distance(lat1, lng1, lat2, lng2) {
  console.log(lat1, lng1, lat2, lng2)
  var radLat1 = lat1 * Math.PI / 180.0
  var radLat2 = lat2 * Math.PI / 180.0
  var a = radLat1 - radLat2;
  var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
  s = s * 6378.137;
  s = Math.round(s * 10000) / 10000;
  return s
},

// 计算相差时间
time(startTime,endTime){
  let difftime = endTime - startTime;
  return difftime/1000
},
// 获取学生时间和信息
async getTimeAndLocation(){
  // 调用函数时，传入new Date()参数，返回值是日期和时间
   app.globalData.time = util.formatTime(new Date());
   app.globalData.timeStamp = new Date(app.globalData.time).getTime()
   var   that = this
 //  获取位置信息
 await wx.getLocation({
   type: 'wgs84',
   isHighAccuracy:true,
   success (res) {
     app.globalData.location = res
     console.log(app.globalData)
     if(!app.globalData.allInfo){
      wx.showModal({
        title: '提示',
        content: '请先绑定用户',
        showCancel: false,
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '../select/select',//跳转到绑定账户页面
            })
          } 
        }
      })  
    }
    else{
      that.canSign(scene)
    }
   }
  })
},

// 获取签到详情信息
getTeacherInfo(_id){
  db.collection('sign_in_history').doc(_id).get().then(res=>{
    teacherLongitude = res.data.longitude
    teacherLatitude = res.data.latitude
    teacherTimeStamp = res.data.timeStamp
  })


},
onGetOpenid: function () {
  // 调用云函数
  wx.cloud.callFunction({
    name: 'login',
    data: {},
    success: res => {
      app.globalData.openid = res.result.openid
      if (!app.globalData.allInfo) {
        // 查询用户信息
        db.collection("users").where({
         openid: app.globalData.openid
       }).get().then(res => {
         app.globalData.allInfo = res.data[0]     
         })
   }
    },
  })
},

// 查询用户信息
getUserInfo(){


     
},



// 判断学生是否可以签到，判断条件，5分钟内，半径500米内
canSign(_id){
  // 获取学生签到距离
   var distance = this.distance(teacherLatitude,teacherLongitude,app.globalData.location.latitude,app.globalData.location.longitude)
   var time = this.time(teacherTimeStamp,app.globalData.timeStamp)
    console.log(distance)
    console.log(time)
   if(distance < 0.5 && time < 300){
      // 将学生姓名写入数据库中
      console.log("进入条件")

      db.collection("sign_in_history").doc(_id).update({
        data:{
          signedStudent: _.unshift(app.globalData.allInfo)
        }, 
        success: function(res) {
          console.log("执行成功")
          wx.showModal({
            title: '提示',
            content: '签到成功',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                console.log('用户点击确定')

                wx.navigateTo({
                  url: '../tabs/tabs', //跳转到指定页面
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
          console.log(res)
        }
      })
      


   }
   else{
     if (distance > 0.5) {
      wx.showModal({
        title: '提示',
        content: '与老师距离过远',
        showCancel: false,
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
     }
     else if(time > 300){
      wx.showModal({
        title: '提示',
        content: '超出签到时间',
        showCancel: false,
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
     }
   }
},


async onLoad (query) {
    // scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
    scene = query._id
    console.log(query)
    console.log(scene)
    await this.getTeacherInfo(scene)
    await this.onGetOpenid()
   
   

  }
})
